package cn.itcast.service.impl;

import cn.itcast.mapper.*;
import cn.itcast.pojo.*;
import cn.itcast.rabbitmq.service.RabbitmqService;
import cn.itcast.service.UserService;
import cn.itcast.util.*;
import cn.web.web_module.entity.WithdrawRechargeInfo;
import cn.web.web_module.mapper.WithdrawRechargeInfoMapper;
import cn.web.web_module.util.IconPath;
import cn.wx.WXPayUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

import static cn.itcast.util.OrderNumber.getOrderIdByTime;

/**
 * @author 辉
 * @title: UserServiceImpl
 * @projectName wx_shop
 * @description: TODO
 * @date 2019/6/1716:27
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    cn.itcast.mapper.userMapper userMapper;

    @Resource
    cn.itcast.mapper.orderMapper orderMapper;

    @Resource
    cn.itcast.mapper.accountMapper accountMapper;

    @Resource
    gzhMapper gzhMapper;

    @Resource
    cn.itcast.mapper.earningsMapper earningsMapper;

    @Resource
    withdrawMapper withdrawMapper;

    @Resource
    infoMapper infoMapper;

    @Resource
    helpCenterMapper helpCenterMapper;

    @Resource
    private RabbitmqService rabbitmqService;

    @Resource
    private WithdrawRechargeInfoMapper withdrawRechargeInfoMapper;




    @Resource
    private horsemanMapper horsemanMapper;

    @Override
    public boolean updateUserInfo(user user) {
        user user1 = userMapper.selectByPrimaryKey(user.getOpenId());
        if(user1==null){
            return false;
        }else {
            int i = userMapper.updateByPrimaryKeySelective(user);
            if(i==1){
                return true;
            }else{
                return false;
            }
        }

    }

    @Override
    public user findUserInfo(String openId) {
        return userMapper.selectByPrimaryKey(openId);
    }

    @Override
    public int findCountOrder(String openId) {
        orderExample oEx = new orderExample();
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        return orderMapper.countByExample(oEx);

    }

    @Override
    public double findCountEarning(String openId) {
        double count = 0.00;

        accountExample aEx = new accountExample();
        accountExample.Criteria criteria = aEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        criteria.andAccountTypeidEqualTo(2);

        List<account> accounts = accountMapper.selectByExample(aEx);
        if(accounts.isEmpty()){
            return count;
        }else {
            count = accounts.get(0).getAccountMoneyRental();
            return count;
        }

//        orderExample oEx = new orderExample();
//        orderExample.Criteria criteria = oEx.createCriteria();
//        criteria.andOpenIdEqualTo(openId);
//        criteria.andOrderStateEqualTo("已完成");
//        List<order> orders = orderMapper.selectByExample(oEx);
//        for (int i=0;i<orders.size();i++){
//            if(StringUtils.isNotBlank(ObjectUtils.toString(orders.get(i).getPayOrderMoney()))){
//                count = DoubleUtils.add(count, orders.get(i).getPayOrderMoney());
//            }
//        }
//        orderExample oExx = new orderExample();
//        orderExample.Criteria criteriax = oEx.createCriteria();
//        criteriax.andOpenIdEqualTo(openId);
//        criteriax.andOrderStateEqualTo("已评价");
//        List<order> orderxs = orderMapper.selectByExample(oExx);
//        for (int i=0;i<orderxs.size();i++){
//            if(StringUtils.isNotBlank(ObjectUtils.toString(orderxs.get(i).getPayOrderMoney()))){
//                count = DoubleUtils.add(count, orderxs.get(i).getPayOrderMoney());
//            }
//        }

    }

    @Override
    public boolean addDistribution(String openId,String distribution) {
        user user = userMapper.selectByPrimaryKey(openId);
        if(!openId.equals(distribution) && user.getUserOneDistribution()==null){
            //添加消息记录
            info infoone = new info();
            infoone.setOpenid(distribution);
            infoone.setUserOpenid(openId);
            infoone.setInfoTitle("成功推广一级伙伴");
            infoone.setInfoType("推广通知");
            infoone.setInfoContent("您推广的用户："+user.getNickName()+"成功的成为了你的环保伙伴");
            infoone.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/huoban-icon.png");
            infoone.setInfoTime(new Date());

            infoMapper.insertSelective(infoone);
            user.setUserOneDistribution(distribution);
            String TwoOpenId = userMapper.selectByPrimaryKey(distribution).getUserOneDistribution();
            if(TwoOpenId!=null && !TwoOpenId.equals(openId)){
                user.setUserTwoDistribution(TwoOpenId);
                //添加消息记录
                info infotwo = new info();
                infotwo.setOpenid(TwoOpenId);
                infotwo.setUserOpenid(openId);
                infotwo.setInfoTitle("成功推广二级伙伴");
                infotwo.setInfoType("推广通知");
                infotwo.setInfoContent("您的伙伴"+userMapper.selectByPrimaryKey(distribution).getNickName()+"成功推广的用户："+user.getNickName()+"成为了您的二级环保伙伴");
                infotwo.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/huoban-icon.png");
                infotwo.setInfoTime(new Date());

                infoMapper.insertSelective(infotwo);
            }
            int i = userMapper.updateByPrimaryKeySelective(user);
            if(i==1){
                return true;
            }else {
                return false;
            }
        }else {
            log.debug("已经存在推荐人，或者推荐人为自己");
            return false;
        }

    }


    @Override
    public String findUserToken(String openId) throws IOException {
        user user = userMapper.selectByPrimaryKey(openId);
        if(user.getUserNative()==null||user.getUserNative().equals("")){
            String url;
            url = postMiniqrQr(openId,gzhMapper.selectByPrimaryKey(3).getAccessToken());
            //判断生成的二维码是否可以打开
            boolean urlImage = urlImg(url);
            if(urlImage == false){ //图片打不开
                //把服务器上的图片删除
                boolean delImage = delPath(openId);
                if(delImage == true){   //删除成功
                    //再次生成
                    url = postMiniqrQr(openId,gzhMapper.selectByPrimaryKey(3).getAccessToken());
                }
            }
            user.setUserNative(url);
            userMapper.updateByPrimaryKeySelective(user);
            return url;
        }else {
            //判断二维码是否打不开
            boolean flag = urlImg(user.getUserNative());
            if(flag == false){  //图片打不开
                //把服务器上的图片删除
                boolean del = delPath(openId);
                if(del == true){    //删除成功
                    //再次生成
                    String imgS = postMiniqrQr(openId,gzhMapper.selectByPrimaryKey(3).getAccessToken());
                    log.info("再次生成小程序二维码：{}",imgS);
                    user userInfo = userMapper.selectByPrimaryKey(openId);
                    userInfo.setUserNative(imgS);
                    userMapper.updateByPrimaryKeySelective(userInfo);
                }
            }
            return user.getUserNative();
        }
    }

    /**
     * 功能描述: <br>
     * 〈删除服务器上面打不开的二维码图片〉
     * @Author: lyy
     * @Date: 2020/9/14 16:22
     * @Param: [openId]
     * @Return: java.lang.String
     */
    public boolean delPath(String openId){
//        File file = new File("/usr/tomcat/images/dhn/icon/ewm/"+openId+".jpg"); //松注释
        File file = new File(IconPath.ICONPATH +"icon/ewm/"+openId+".jpg");
        if(!file.exists()){            //如果文件夹不存在
            log.info("该二维码图片地址不存在！！！");
            return false;
        }else{
            file.delete();
            log.info("成功删除该图片二维码！！！");
            return true;
        }
    }

    public boolean urlImg(String usr) throws IOException {
        URL url = new URL(usr);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        BufferedImage image = ImageIO.read(connection.getInputStream());
        if(image==null) return false;
        else return true;
    }

    /**
     *
     * @Description: 推广地址二维码无法访问,清除用户推广地址二维码
     *
     * @auther: 张松
     * @date: 9:28 2020/8/8
     * @param: [openId]
     * @return: void
     *
     */
    public void deleteUserNative(String openId){
        user user = userMapper.selectByPrimaryKey(openId);
        user.setUserNative("");
        userMapper.updateByPrimaryKeySelective(user);
    }


    /**
     * 生成带参小程序二维码
     * @param scene	要输入的内容
     * @param accessToken	token
     */
    String postMiniqrQr(String scene, String accessToken) {
        try{
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true); // 打开写入属性
            httpURLConnection.setDoInput(true); // 打开读取属性
            httpURLConnection.setRequestMethod("POST");// 提交方式
            // 不得不说一下这个提交方式转换！！真的坑。。改了好长时间！！一定要记得加响应头
            httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");// 设置响应头
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", scene); // 你要放的内容
            paramJson.put("path", "pages/index/index");
            paramJson.put("width", 430); // 宽度
            paramJson.put("auto_color", true);

            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();

            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());

            //创建一个空文件
//            OutputStream os = new FileOutputStream(new File("/usr/tomcat/images/dhn/icon/ewm/"+scene+".jpg"));    //松注释
            OutputStream os = new FileOutputStream(new File("/usr/local/nginx8181/data/dhn/icon/ewm/"+scene+".jpg"));

//            OutputStream os = new FileOutputStream(new File("E:\\images\\"+scene+".jpg"));

            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1)
            {
                os.write(arr, 0, len);
                os.flush();
            }

            os.close();

            return "https://www.dhnep.cn:8181/dhn/icon/ewm/"+scene+".jpg";

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "";
    }


    @Override
    public Map<String,List<user>> findUserDistribution(String openId) {
//        userExample uEx = new userExample();
//        userExample.Criteria criteria = uEx.createCriteria();
//        criteria.andUserOneDistributionEqualTo(openId);
//        uEx.setOrderByClause("create_time DESC");
        List<user> users = userMapper.findOneDistribution(openId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
        Map<String,List<user>> userMap = new HashMap<>();
        if(!users.isEmpty()){
            for (user user : users) {
                user.setCreateTime_String(sdf.format(user.getCreateTime()));
            }
            for(int i = 0;i<users.size();i++){
//                userExample twoUEx = new userExample();
//                userExample.Criteria criteria1 = twoUEx.createCriteria();
//                criteria1.andUserOneDistributionEqualTo(users.get(i).getOpenId());
//                twoUEx.setOrderByClause("create_time DESC");
                List<user> users1 = userMapper.findTwoDistribution(users.get(i).getOpenId());
                if(!users1.isEmpty()){
                    for (user user : users1) {
                        user.setCreateTime_String(sdf.format(user.getCreateTime()));
                    }
                    users.get(i).setTwoUsers(users1);
                }
            }
            userMap.put("one",users);
        }else {
            userMap.put("one",null);
        }





        return userMap;
    }

    @Override
    public List<earnings> findAllEarnings(String openId) {
        earningsExample eEx = new earningsExample();
        earningsExample.Criteria criteria = eEx.createCriteria();
        criteria.andOpenidEqualTo(openId);
        return earningsMapper.selectByExample(eEx);
    }

    @Override
    public Map<String, List<earnings>> findTypeEarnings(String openId) {
        Map<String,List<earnings>> earningsMap = new HashMap<>();
        earningsExample eEx = new earningsExample();
        earningsExample.Criteria criteria = eEx.createCriteria();
        criteria.andOpenidEqualTo(openId);
        criteria.andSourceEqualTo("订单消费");

        earningsMap.put("my",earningsMapper.selectByExample(eEx));

        earningsExample oneeEx = new earningsExample();
        earningsExample.Criteria onecriteria = oneeEx.createCriteria();
        onecriteria.andOpenidEqualTo(openId);
        onecriteria.andSourceEqualTo("一级分销");
        List<earnings> oneEarnings = earningsMapper.selectByExample(oneeEx);
        Collections.reverse(oneEarnings);
        earningsMap.put("one",oneEarnings);


        earningsExample twoeEx = new earningsExample();
        earningsExample.Criteria twocriteria = twoeEx.createCriteria();
        twocriteria.andOpenidEqualTo(openId);
        twocriteria.andSourceEqualTo("二级分销");
        List<earnings> twoEarnings = earningsMapper.selectByExample(twoeEx);
        Collections.reverse(twoEarnings);
        earningsMap.put("two",twoEarnings);


        earningsExample twoEExBonus = new earningsExample();
        earningsExample.Criteria twoCriteriaBonus = twoEExBonus.createCriteria();
        twoCriteriaBonus.andOpenidEqualTo(openId);
        twoCriteriaBonus.andSourceEqualTo("首单奖金");
        List<earnings> twoEEarnings = earningsMapper.selectByExample(twoEExBonus);
        Collections.reverse(twoEEarnings);
        earningsMap.put("bonus",twoEEarnings);


        return earningsMap;

    }


    @Override
    public boolean sendOrder(Integer orderId, String openId, String name,String DispatchOpenId) {
        order order = new order();
        order.setOrderState("进行中");
        order.setHorsemanAccount(openId);
        order.setHorsemanName(name);
        order.setId(orderId);
        order.setDispatchOpenId(DispatchOpenId);
        int i = orderMapper.updateByPrimaryKeySelective(order);

        order dataOrder = orderMapper.selectByPrimaryKey(orderId);
        if(i==1){
            log.debug("开始推送");
            //推送消息给骑手，提醒接单
            String token = gzhMapper.selectByPrimaryKey(2).getAccessToken();


            Template template=new Template();
            template.setTemplate_id("OjiwqySOKJYbrlVYMxX8b4GAUwHdhQISHEf3FH6dgH0");
            template.setTouser(openId);
            template.setPage("pages/order/main");
            List<TemplateParam> paras=new ArrayList<TemplateParam>();
            paras.add(new TemplateParam("time1",dataOrder.getOrderVisitTime().substring(0,5)));
            paras.add(new TemplateParam("thing3",dataOrder.getPayProductType().substring(0,Math.min(19,dataOrder.getPayProductType().length()))));
            paras.add(new TemplateParam("thing4",dataOrder.getPayForecastWeight()));
            paras.add(new TemplateParam("thing5",dataOrder.getUserArea().substring(dataOrder.getUserArea().indexOf("市")+1,Math.min(dataOrder.getUserArea().indexOf("市")+20,dataOrder.getUserArea().length()))));
            paras.add(new TemplateParam("phone_number10",dataOrder.getUserPhone()));
            template.setTemplateParamList(paras);
            String requestUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
            requestUrl=requestUrl.replace("ACCESS_TOKEN", token);

            System.out.println(template.toJSON());
            net.sf.json.JSONObject jsonResult= CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());
            if(jsonResult!=null){
                System.out.println(jsonResult);
                int errorCode=jsonResult.getInt("errcode");
                String errorMessage=jsonResult.getString("errmsg");
                if(errorCode==0){
                    log.debug("提醒骑手接单Send Success");
                }else{
                    log.debug("订阅消息发送失败:"+errorCode+","+errorMessage);
                }
            }




//            String createUlr = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+token;
//            Map<String,String> param = new HashMap<>();
//            param.put("touser",openId);
//            param.put("template_id","OjiwqySOKJYbrlVYMxX8b3gbnlg3r4l13qlH87nGrJY");
//            param.put("page","pages/order/main");
//            Map<String,Object> data = new HashMap<>();
//            data.put("time1",new HashMap<String,String>().put("value",dataOrder.getOrderVisitTime()));
//            data.put("thing3",new HashMap<String,String>().put("value",dataOrder.getPayProductType()));
//            data.put("thing4",new HashMap<String,String>().put("value",dataOrder.getPayForecastWeight()));
//            data.put("thing5",new HashMap<String,String>().put("value",dataOrder.getUserArea()));
//            data.put("phone_number10",new HashMap<String,String>().put("value",dataOrder.getUserPhone()));
//            param.put("data",data.toString());
//            String result = doPost(createUlr, param);
//            log.debug("推送消息:"+result);

            //com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
            //log.debug(object.getString("open_appid"));

            return true;
        }else {
            return false;
        }
    }



    @Override
    public List<withdraw> findUnWithdraw() {
        withdrawExample withdrawExample = new withdrawExample();
        withdrawExample.Criteria criteria = withdrawExample.createCriteria();
        criteria.andStateEqualTo("已申请");
        return withdrawMapper.selectByExample(withdrawExample);
    }


    @Override
    public Boolean checkWithdraw(Integer id) {


        withdraw withdraw = withdrawMapper.selectByPrimaryKey(id);
        accountExample aEx = new accountExample();
        accountExample.Criteria criteria = aEx.createCriteria();
        criteria.andOpenIdEqualTo(withdraw.getOpenId());
        List<account> accounts = accountMapper.selectByExample(aEx);
        account account = accounts.get(0);
        Double withdrawNum = withdraw.getNum(); //提现金额
        if(new BigDecimal(account.getAccountMoneyBalance()).compareTo(new BigDecimal(withdrawNum))!=-1){
            try{
                //生成的随机字符串
                String nonce_str = WXPayUtil.generateNonceStr();
                //获取客户端的ip地址
                //获取本机的ip地址
                InetAddress addr = null;
                try {
                    addr = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                String spbill_create_ip = addr.getHostAddress();
                //支付金额，需要转成字符串类型，否则后面的签名会失败
                //int  total_fee=1;
                String money = new BigDecimal(withdrawNum.toString()).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).toString();
                log.debug("提现金额"+money);
                //商品描述
                String body = "环保金提现";

                //提现用户类型
                String appid = "";
                if(withdraw.getUserType().equals("1")){
                    appid = "wx51d55df222d9901e";
                }else if(withdraw.getUserType().equals("0")){
                    appid = "wx1cf12dee9dbfe13c";
                }else if(withdraw.getUserType().equals("2")){
                    appid = "wx578244d5b6022c06";
                }

                //String out_trade_no = WXPayUtil.generateNonceStr();
                //统一下单接口参数
                HashMap<String, String> data = new HashMap<String, String>();
                data.put("mch_appid", appid);
                data.put("mchid", "1550181801");
                data.put("nonce_str", nonce_str);
                data.put("desc", body);
                data.put("partner_trade_no", withdraw.getNumber());
                data.put("openid", withdraw.getOpenId());
                data.put("check_name", "NO_CHECK");
                data.put("amount", money);
                data.put("spbill_create_ip", spbill_create_ip);

                String sign = WXPayUtil.generateSignature(data, "0B2DC615EA4F78BC4B216AEA1A6DA63B");//商户密码
                data.put("sign", sign);
                String xml = WXPayUtil.mapToXml(data);//将所有参数(map)转xml格式



                //企业付款
                String macPayUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

//            String xmlStr = HttpClientUtil.sendPost(macPayUrl, xml);
                String xmlStr = HttpClientUtil.posts(macPayUrl, xml);

                Map<String, String> reMap = WXPayUtil.xmlToMap(xmlStr);
                log.debug(reMap.toString());
                if (CollectionUtil.isNotEmpty(reMap) && "SUCCESS".equals(reMap.get("result_code"))) {
                    //成功需要进行的逻辑操作
                    log.debug("提现成功");
                    //修改骑手账户金额,修改提现记录状态

                    //提现之后的金额
                    double sub = DoubleUtils.sub(account.getAccountMoneyBalance(), withdrawNum);
                    account.setAccountMoneyBalance(sub);
                    log.debug("提现后账户金额");
                    log.debug(account.getAccountMoneyBalance().toString());
                    int i = accountMapper.updateByPrimaryKeySelective(account);
                    if(i==1){
                        //修改提现记录状态
                        withdraw.setState("已到账");
                        withdraw.setBillTime(new Date());
                        withdraw.setCountnum(sub);
                        withdrawMapper.updateByPrimaryKeySelective(withdraw);

                        //添加消息记录
                        info info = new info();
                        info.setOpenid(withdraw.getOpenId());
                        info.setInfoTitle("提现成功提醒");
                        info.setInfoType("提现消息");
                        info.setInfoContent("您提现申请已经通过了，提现金额为："+ withdrawNum +",环保佣金已经到您的微信零钱了，请注意查收。");
                        info.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/money-icon.png");
                        info.setInfoTime(new Date());

                        infoMapper.insertSelective(info);

                        //微信提醒用户提现到账
                        this.rabbitmqService.sendWithdrawCash(withdraw.getOpenId(),String.valueOf(withdrawNum));

                        earnings earnings = new earnings();
                        earnings.setAccountId(account.getAccountId());
                        earnings.setName(account.getAccountName());
                        earnings.setOpenid(account.getOpenId());
                        earnings.setSource("提现记录");
                        earnings.setNumber(getOrderIdByTime());
                        earnings.setState("已提现");
                        earnings.setNum(withdrawNum);
                        earnings.setEarningsExplain("用户提现");
                        //用户提现后的账户余额
                        earnings.setCountnum(sub);
                        earningsMapper.insertSelective(earnings);

//                      ------------------------------------------提现成功记录到WithdrawRechargeInfo中------------------------------------------
                        String isHorsemanOpenId = withdraw.getOpenId();
                        List<horseman> horsemen = horsemanMapper.selectHorsemanOpenId(isHorsemanOpenId);

                        if (horsemen.size()>0||!horsemen.isEmpty()){
                            List<order> orders = orderMapper.selectHorsemanStocksOrder(isHorsemanOpenId);
                            int orderId = 0;
                            if (orders.size()>0||!orders.isEmpty()){
                                orderId=orders.get(0).getId();
                            }
                            WithdrawRechargeInfo withdrawRechargeInfo =new WithdrawRechargeInfo();
                            withdrawRechargeInfo.setOrderId(orderId);
                            withdrawRechargeInfo.setWithdrawMoney(Long.parseLong(money)/100);
                            withdrawRechargeInfo.setWithdrawId(withdraw.getId());
                            withdrawRechargeInfo.setHorsemanAccount(horsemen.get(0).getOpenId());
                            withdrawRechargeInfo.setHorsemanName(horsemen.get(0).getHorsemanName());
                            withdrawRechargeInfo.setWithdrawTime(new Date());
                            withdrawRechargeInfoMapper.insertSelective(withdrawRechargeInfo);
                        }

//                        ------------------------------------------------------------------------------------

                        return true;
                    }else {
                        return false;
                    }


                }else {
                    //添加消息记录
                    info info = new info();
                    info.setOpenid(withdraw.getOpenId());
                    info.setInfoTitle("提现失败提醒");
                    info.setInfoType("提现消息");
                    info.setInfoContent("很抱歉，您提现金额为："+ withdrawNum +"的提现申请没有通过审核,请查看环保金是否有什么异常，如有疑问请拨打客服电话。");
                    info.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/money-icon.png");
                    info.setInfoTime(new Date());

                    infoMapper.insertSelective(info);

                    if (CollectionUtil.isNotEmpty(reMap)) {
                        //resMap.put("msg","提现失败:"+reMap.get("err_code") + ":" + reMap.get("err_code_des"));
                        log.debug("提现失败");
                        return false;
                    }
                    //resMap.put("code",0);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return true;
    }

    @Override
    public Boolean lostEffect(Integer id){
        withdraw withdraw = new withdraw();
        withdraw.setId(id);
        withdraw.setState("已失效");
        int i = withdrawMapper.updateByPrimaryKeySelective(withdraw);
        //添加消息记录
        info info = new info();
        info.setOpenid(withdrawMapper.selectByPrimaryKey(id).getOpenId());
        info.setInfoTitle("提现失败提醒");
        info.setInfoType("提现消息");
        info.setInfoContent("很抱歉，您提现金额为："+withdrawMapper.selectByPrimaryKey(id).getNum()+"的提现申请没有通过审核,请查看环保金是否有什么异常，如有疑问请拨打客服电话。");
        info.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/money-icon.png");
        info.setInfoTime(new Date());

        infoMapper.insertSelective(info);

        //用户申请提现审核不通过
        this.rabbitmqService.WithdrawFailure(withdrawMapper.selectByPrimaryKey(id).getOpenId(),String.valueOf(withdrawMapper.selectByPrimaryKey(id).getNum()));

        if(i != 1){
            return false;
        }
        return true;
    }


    @Override
    public Map<String, Object> getOrderById(Integer page, Integer limit, String openId,String state ) {
        orderExample orderExample = new orderExample();
        cn.itcast.pojo.orderExample.Criteria criteria = orderExample.createCriteria();



        criteria.andOpenIdEqualTo(openId);
        if(!state.equals("")){
            criteria.andOrderStateEqualTo(state);
        }

        //返回符合查询条件的总记录数
        int count = orderMapper.countByExample(orderExample);

        orderExample.setOrderByClause("order_time DESC");
        //分页
        PageHelper.startPage(page,limit);
        //查询所有符合搜索条件的订单
        List<order> orderList = orderMapper.selectByExample(orderExample);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("count",count);
        map.put("orderList",orderList);

        return map;
    }

    @Override
    public boolean isPhone(String openId) {
        user user = userMapper.selectByPrimaryKey(openId);
        return user.getUserPhone()==null;
    }

    @Override
    public List<helpCenter> findAllHelp(){

        return helpCenterMapper.selectByExample(new helpCenterExample());
    }

    @Override
    public helpCenter findHelp(Integer id){


        return helpCenterMapper.selectByPrimaryKey(id);
    }

    @Override
    public  String findUserPhone(String encryptedData, String iv,String openId){
        log.debug(iv);
        log.debug(encryptedData);
        user user = userMapper.selectByPrimaryKey(openId);
        String result = WXPhoneUtil.wxDecrypt(encryptedData, user.getSessionKey(), iv);
        JSONObject jo =JSONObject.parseObject(result);
        if (jo.containsKey("phoneNumber")) {
            String phone = jo.getString("phoneNumber");
            if(StringUtils.isNoneBlank(phone)){
                return phone;
            }else {
                return "";
            }
        }
//        try {
//            URLEncoder.encode(iv,"UTF-8").replace("%3D","=").replace("%2F","/");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
//        Cipher cipher = null;
//        try {
//            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
//            e.printStackTrace();
//        }
//        SecretKeySpec keySpec = new SecretKeySpec(user.getSessionKey().getBytes(), "AES");
//        try {
//            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
//        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
//            e.printStackTrace();
//        }
//        //解析解密后的字符串  
//        try {
//            return new String(cipher.doFinal(encryptedData.getBytes()), StandardCharsets.UTF_8);
//        } catch (IllegalBlockSizeException | BadPaddingException e) {
//            e.printStackTrace();
//        }

        return "";
    }

    @Override
    public Map<String,Object> getPromotionManagementOne(String openId,Integer pageNum,Integer pageSize) {
        Map<String,Object> PromotionManagement = new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);
        List<user> oneDistribution = userMapper.findOneDistribution(openId);
        PageInfo pageInfo = new PageInfo(oneDistribution);
        PromotionManagement.put("one",pageInfo);
        return PromotionManagement;
    }

    @Override
    public Map<String,Object> getPromotionManagementTwo(String openId,Integer pageNum,Integer pageSize) {
        Map<String,Object> PromotionManagement = new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);
        List<user> twoDistribution = userMapper.selectTwoDistribution(openId);
        PageInfo pageInfo2 = new PageInfo(twoDistribution);
        PromotionManagement.put("two",pageInfo2);
        return PromotionManagement;
    }


    /**
     *功能：查询昨天新增的用户数和查询他们是谁推广的
     * @author 张松
     * @date 2020/6/24
     * @param
     * @return java.util.List<cn.itcast.pojo.user>
     */
    @Override
    public List<user> getYesterdayAdduser() {
        List<user> yesterdayAdduser = userMapper.getYesterdayAdduser();
        return yesterdayAdduser;
    }

    /**
     *
     * @Description: 获取每日新增用户
     *
     * @auther: 张松
     * @date: 9:08 2020/7/18
     * @param: [intDate]  查看相隔天数
     * @return: void
     *
     */
    @Override
    public List<user> getEveryDayAllAddUser(Integer intDate){
        return userMapper.getEveryDayAdduser(intDate);
    }



    /**
     *
     * @Description: 查看全部用户数
     *
     * @auther: 张松
     * @date: 14:23 2020/6/26
     * @param: []
     * @return: java.lang.Integer
     *
     */
    @Override
    public Integer selectAllUserCount() {
        return userMapper.selectAllUserCount();
    }


    /**
     *
     * @Description:  查看是否有这个手机号
     *
     * @auther: 张松
     * @date: 9:20 2020/7/14
     * @param: [phone]
     * @return: cn.itcast.pojo.user
     *
     */
    @Override
    public user selectUserPhone(String phone) {
        user user = userMapper.selectUserPhone(phone);
        return user;
    }


}
